//
// Created by wsl on 2024/3/8.
//

#include "SqStack.h"

DataStructure_Warning_Unused
int SqStack_length(SqStack stack)
{
	if (NULL == stack)
		return -1;

	return stack->length;
}

DataStructure_Warning_Unused
SqStack SqStack_create(size_t dataSize, uint8_t initSize)
{
	if (initSize < 1)
		return NULL;

	//创建栈对象
	SqStack stack = DataStructure_AllocT(SqStk);
	if (NULL == stack)
	{
		DataStructure_Overflow_Handler();

		return NULL;
	}

	//创建元素空间
	T temp = DataStructure_Alloc(dataSize * initSize);
	if(NULL == temp)
	{
		DataStructure_MemoryFree(stack);

		DataStructure_Overflow_Handler();

		return NULL;
	}

	//初始化对象
	stack->dataSize = dataSize;
	stack->length = 0;
	stack->capacity = initSize;
	stack->base = temp;
	stack->initSize = initSize;

	//返回对象
	return stack;
}

DataStructure_Warning_Unused
Status SqStack_isEmpty(SqStack stack)
{
	if (NULL == stack)
		return TRUE;

	return (stack->length <= 0 ? TRUE : FALSE);
}

DataStructure_Warning_Unused
Status SqStack_push(SqStack stack, T e)
{
	if (NULL == stack)
		return FALSE;

	//扩容
	if (stack->length >= stack->capacity)
	{
		//当前容量 + 初始容量 来扩容
		size_t newCapacity = (stack->capacity + stack->initSize);
		T temp = DataStructure_Reallocation(stack->base, newCapacity * stack->dataSize);
		if (NULL == temp)
		{
			DataStructure_Overflow_Handler();

			return OVERFLOW;
		}
		stack->base = temp;
		stack->capacity = newCapacity;
	}

	//将数据拷贝到栈中
	DataStructure_MemoryCpy((uint8_t*)stack->base + stack->length * stack->dataSize, e, stack->dataSize);

	stack->length++;

	return TRUE;
}

DataStructure_Warning_Unused
Status SqStack_top(SqStack stack, T buf)
{
	if(SqStack_isEmpty(stack))
		return FALSE;

	DataStructure_MemoryCpy(buf, (uint8_t*)stack->base + (stack->length - 1) * stack->dataSize, stack->dataSize);

	return TRUE;
}

DataStructure_Warning_Unused
Status SqStack_pop(SqStack stack, T buf)
{
	if(SqStack_isEmpty(stack))
		return FALSE;

	DataStructure_MemoryCpy(buf, (uint8_t*)stack->base + (stack->length - 1) * stack->dataSize, stack->dataSize);

	stack->length--;

	return TRUE;
}

DataStructure_Warning_Unused
Status SqStack_clear(SqStack stack)
{
	if (SqStack_isEmpty(stack))
		return FALSE;

	//栈容量过大，回收部分内存
	if (stack->capacity > stack->initSize * 2)
	{
		size_t newCapacity = stack->initSize;
		T temp = DataStructure_Reallocation(stack->base, newCapacity * stack->dataSize);
		if (NULL == temp)
		{
			DataStructure_Overflow_Handler();

			return OVERFLOW;
		}
		stack->base = temp;
		stack->capacity = newCapacity;
	}

	stack->length = 0;

	return TRUE;
}

DataStructure_Warning_Unused
Status SqStack_destroy(SqStack *stack)
{
	if (NULL == stack || NULL == *stack)
		return FALSE;

	//释放容器
	DataStructure_MemoryFree((*stack)->base);

	//释放对象本身
	DataStructure_MemoryFree(*stack);

	*stack = NULL;

	return TRUE;
}




